package com.ccn.qrcode.utils.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.MapType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

public class JSONBeanUtils {
    private static final Logger log = LoggerFactory.getLogger(JSONBeanUtils.class);
    private static final ObjectMapper MAPPER = new ObjectMapper();

    public JSONBeanUtils() {
    }
    
    public static String objectToJson(Object data) throws Exception {
        try {
            String result = MAPPER.writeValueAsString(data);
            return result;
        } catch (JsonProcessingException var2) {
            log.error("bean转换为json失败！", var2);
            throw new Exception("bean转换为json失败！");
        }
    }

    public static <T> T jsonToBean(String jsonData, Class<T> beanType) throws Exception {
        try {
            T result = MAPPER.readValue(jsonData, beanType);
            return result;
        } catch (Exception var3) {
            log.error("json转换为bean失败！", var3);
            throw new Exception("json转换为bean失败！");
        }
    }

    public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) throws Exception {
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, new Class[]{beanType});

        try {
            List<T> resultList = (List)MAPPER.readValue(jsonData, javaType);
            return resultList;
        } catch (Exception var4) {
            log.error("json转换为List<bean>失败！", var4);
            throw new Exception("json转换为List<bean>失败！");
        }
    }

    public static <K, V> Map<K, V> jsonToMap(String jsonData, Class<K> keyType, Class<V> valueType) throws Exception {
        MapType javaType = MAPPER.getTypeFactory().constructMapType(Map.class, keyType, valueType);

        try {
            Map<K, V> resultMap = (Map)MAPPER.readValue(jsonData, javaType);
            return resultMap;
        } catch (Exception var5) {
            log.error("json转换为Map失败！", var5);
            throw new Exception("json转换为Map失败！");
        }
    }

    public static <T> T mapToBean(Map<String, Object> keyType, Class<T> valueType) throws Exception {
        return jsonToBean(mapToJson(keyType), valueType);
    }

    public static String mapToJson(Map<String, Object> keyType) throws Exception {
        try {
            String json = MAPPER.writeValueAsString(keyType);
            return json;
        } catch (Exception var2) {
            log.error("map转换JSON失败！");
            throw new Exception("map转换JSON失败！");
        }
    }

    static {
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
}
